<template>
  <view class="container">
    <!-- 加载状态 -->
    <view v-if="loading" class="loading-wrapper">
      <uni-load-more status="loading" content="加载中..."></uni-load-more>
    </view>

    <!-- 已报名信息展示 -->
    <template v-else-if="regInfo.regStatus !== undefined">
      <view class="header">
        <text class="title">{{ regInfo.realName }}的报名信息</text>
        <view class="status" :class="statusClass">
          {{ statusText }}
        </view>
      </view>

      <view class="card">
        <view class="info-item">
          <text class="label">姓　　名：</text>
          <text class="value">{{ regInfo.realName }}</text>
        </view>
        <view class="info-item">
          <text class="label">性　　别：</text>
          <text class="value">{{ genderMap[regInfo.gender] || '未知' }}</text>
        </view>
        <view class="info-item">
          <text class="label">联系方式：</text>
          <text class="value">{{ regInfo.contact }}</text>
        </view>
        <view class="info-item">
          <text class="label">邮　　箱：</text>
          <text class="value">{{ regInfo.email }}</text>
        </view>
        <view class="info-item">
          <text class="label">年　　级：</text>
          <text class="value">{{ regInfo.grade || '暂无' }}</text>
        </view>
        <view class="info-item">
          <text class="label">专　　业：</text>
          <text class="value">{{ regInfo.major || '暂无' }}</text>
        </view>
        <view class="info-item">
          <text class="label">报名时间：</text>
          <text class="value">{{ formatTime(regInfo.regTime) }}</text>
        </view>
        <view class="info-item" v-if="regInfo.remark">
          <text class="label">审核备注：</text>
          <text class="value remark">{{ regInfo.remark }}</text>
        </view>

        <view class="footer" v-if="regInfo.regStatus === '0'">
          <button class="button" type="warn" @click="handleCancel">取消报名</button>
        </view>
      </view>
    </template>

    <!-- 未报名表单 -->
    <template v-else>
      <view class="header">
        <text class="title">活动报名</text>
		<text style="font-size: small;" v-if="requiredIntegral">需要{{requiredIntegral}}可用积分</text>
        <text class="sub-title">请填写以下报名信息</text>
      </view>

      <uni-forms ref="form" :model="formData" :rules="rules" class="form-card">
        <uni-forms-item label="真实姓名" name="realName" required>
          <uni-easyinput
            v-model="formData.realName"
            placeholder="请输入真实姓名"
            trim
          />
        </uni-forms-item>

        <uni-forms-item label="性别" name="gender" required>
          <uni-data-checkbox
            v-model="formData.gender"
            :localdata="genders"
          />
        </uni-forms-item>

        <uni-forms-item label="手机号" name="contact">
          <uni-easyinput
            v-model="formData.contact"
            placeholder="请输入手机号"
            type="number"
            maxlength="11"
          />
        </uni-forms-item>

        <uni-forms-item label="邮箱" name="email">
          <uni-easyinput
            v-model="formData.email"
            placeholder="请输入邮箱"
            type="email"
          />
        </uni-forms-item>

        <uni-forms-item label="年级" name="grade">
          <uni-easyinput
            v-model="formData.grade"
            placeholder="例：2023级"
          />
        </uni-forms-item>

        <uni-forms-item label="专业" name="major">
          <uni-easyinput
            v-model="formData.major"
            placeholder="请输入专业名称"
          />
        </uni-forms-item>
    <uni-forms-item label="学号" name="major">
          <uni-easyinput
            v-model="formData.studentNumber"
            placeholder="请输入学号"
          />
        </uni-forms-item>
        <button
          type="primary"
          class="submit-btn"
          :loading="submitting"
          @click="handleSubmit"
        >
          {{ submitting ? '提交中...' : '立即报名' }}
        </button>
      </uni-forms>
    </template>
  </view>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue';
// import http from '@/utils/http';
import { http } from '../../../utils/requestUtil';
const requiredIntegral = ref(null)
const props = defineProps({
  id: String // 活动ID
});

// 数据状态
const loading = ref(true);
const submitting = ref(false);
const regInfo = ref({});
const form = ref();

// 表单数据
const formData = reactive({
  realName: '',
  gender: '0',
  contact: '',
  email: '',
  grade: '',
  major: '',
  studentNumber:''
});

// 选项数据
const genders = ref([
  { value: '0', text: '男' },
  { value: '1', text: '女' }
]);

// 验证规则
const rules = reactive({
  realName: {
    rules: [
      { required: true, errorMessage: '姓名不能为空' },
      { minLength: 2, maxLength: 10, errorMessage: '姓名长度为2-10个字符' }
    ]
  },
  gender: {
    rules: [{ required: true, errorMessage: '请选择性别' }]
  },
  // contact: {
  //   rules: [
  //     { required: true, errorMessage: '手机号不能为空' },
  //     { pattern: /^1[3-9]\d{9}$/, errorMessage: '手机号格式不正确' }
  //   ]
  // },
  // email: {
  //   rules: [
  //     { required: true, errorMessage: '邮箱不能为空' },
  //     { 
  //       pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
  //       errorMessage: '邮箱格式不正确'
  //     }
  //   ]
  // }
});

// 计算属性
const statusText = computed(() => {
  switch (regInfo.value.regStatus) {
    case '0': return '待审核';
    case '1': return '已通过';
    case '2': return '未通过';
    default: return '';
  }
});

const statusClass = computed(() => ({
  'status-waiting': regInfo.value.regStatus === '0',
  'status-success': regInfo.value.regStatus === '1',
  'status-error': regInfo.value.regStatus === '2'
}));

const genderMap = computed(() => ({
  '0': '男',
  '1': '女'
}));

// 方法
const formatTime = (time) => {
  if (!time) return '暂无';
  return time.replace('2025-', '').replace('-', '/');
};

// 加载报名信息
const loadRegistrationInfo = async () => {
	const userInfo = uni.getStorageSync("userInfo")
	formData.grade = userInfo.grade
		formData.major = userInfo.major
			formData.gender = userInfo.sex
	formData.email = userInfo.email
	formData.contact = userInfo.phonenumber
  try {
    const res = await http.get(`/bole/registration/registionInfo/${props.id}`);
	// console.log(res.data)
    regInfo.value = res.data || {};
  } catch (error) {
    console.error('加载报名信息失败:', error);
  } finally {
    loading.value = false;
  }
};

// 提交报名
const handleSubmit = async () => {
	
	if(uni.getStorageSync("userInfo").score < requiredIntegral.value){
		uni.showToast({
			title:"可用积分不足",
			icon:"error"
		})
		return
	}
	if(formData.realName == ''){
		uni.showToast({
			title:'姓名不能为空',
			icon:'error'
		})
		return
	}
  try {
    submitting.value = true;
    
    // 表单验证
    // const valid = await form.value.validate();
    // if (valid) return;

    // 提交数据
		
	await http.post('/bole/registration/user', {
      contentId: props.id,
      ...formData
    })
    uni.showToast({ title: '报名成功', icon: 'success' });
	 
	// setTimeout(()=>{
		await loadRegistrationInfo();
		 await updateUserInfo()
	// },1000)

  } catch (error) {
	  console.log(error)
    uni.showToast({
      title: error.message || '提交失败',
      icon: 'none'
    });
  } finally {
    submitting.value = false;
  }
};

// 取消报名
const handleCancel = async () => {
  uni.showModal({
    title: '确认取消',
    content: '确定要取消报名吗？',
    success: async (res) => {
      if (res.confirm) {
        try {
		
          const res= await http.delete(`/bole/registration/user/${regInfo.value.regId}`);
		  updateUserInfo()
          uni.showToast({ title: '取消成功' });
          regInfo.value = {};
        } catch (error) {
          uni.showToast({ title: '取消失败', icon: 'none' });
        }
      }
    }
  });
};
import { onLoad } from '@dcloudio/uni-app';
import { updateUserInfo } from '../../../utils/tokenUtil';
onLoad((options)=>{
	requiredIntegral.value=options.needscore
	// console.log(uni.getStorageSync("userInfo"))
	  loadRegistrationInfo();
	   updateUserInfo()
})

// 初始化
// onMounted((options) => {
// 	console.log(options)

// });

</script>

<style  scoped>
.container {
  padding: 30rpx;
  min-height: 100vh;
  background-color: #f8f8f8;
}

.header {
  margin-bottom: 40rpx;
}

.header .title {
  font-size: 36rpx;
  font-weight: bold;
  color: #333;
}

.header .sub-title {
  display: block;
  margin-top: 10rpx;
  font-size: 28rpx;
  color: #666;
}

.header .status {
  float: right;
  padding: 8rpx 20rpx;
  border-radius: 40rpx;
  font-size: 24rpx;
}

.header .status.status-waiting {
  background: #fff3e0;
  color: #ff9900;
}

.header .status.status-success {
  background: #e8f5e9;
  color: #4caf50;
}

.header .status.status-error {
  background: #ffebee;
  color: #f44336;
}

.card {
  background: #fff;
  border-radius: 16rpx;
  padding: 30rpx;
  box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.05);
}

.info-item {
  display: flex;
  margin-bottom: 24rpx;
  font-size: 28rpx;
}

.info-item .label {
  width: 160rpx;
  color: #666;
}

.info-item .value {
  flex: 1;
  color: #333;
}

.info-item .value.remark {
  color: #e91e63;
  font-weight: 500;
}

.form-card {
  background: #fff;
  padding: 30rpx;
  border-radius: 16rpx;
}

.form-card :deep(.uni-forms-item__label) {
  width: 140rpx !important;
}

.submit-btn {
  margin-top: 40rpx;
  height: 90rpx;
  border-radius: 45rpx;
}

.footer {
  margin-top: 50rpx;
}

.footer .button {
  height: 80rpx;
  line-height: 80rpx;
  border-radius: 40rpx;
}

.loading-wrapper {
  padding-top: 200rpx;
}    
</style>